<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 车辆加油卡账 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-spin :spinning="loading">
        <!-- 加油卡账填写 -->
        <a-card :bordered="false">
          <title-name title="加油卡账填写"></title-name>
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : 'E'"> </custom-form>
          <!-- 加油卡信息 -->
          <div class="mb12" v-if="editModel != 0">所选单位下的所有加油卡信息如下，请填写充值金额：</div>
          <a-table class="mb20" bordered rowKey="id" :columns="columns" :data-source="loadData" :pagination="false">
            <!-- 充值金额 -->
            <template slot="chargeAmount" slot-scope="text, record">
              <BaseInputNumber
                v-if="editModel == 1"
                :precision="2"
                :min="0"
                v-model="record.chargeAmount"
                placeholder="请输入充值金额"
              />
              <span v-else>{{ text }}</span>
            </template>
          </a-table>
          <a-form-model-item label="油卡转账凭证" prop="fileInfoVOS">
            <div style="margin-top: -3px">
              <template v-if="editModel != 0">
                <l-table :fileAutoLoading="false" businessCode="OF12" :uploadArrys.sync="form.fileInfoVOS"></l-table>
                <div>支持格式：.rar .zip .doc .docx .pdf .jpg .png</div>
              </template>
              <file-link v-else :fileList="form.fileInfoVOS"></file-link>
            </div>
          </a-form-model-item>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button :loading="loading" v-if="editModel != 0" type="primary" class="button_right" @click="handleSubmit"
          >提交</a-button
        >
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { carGasCard } from '@/api/office/vehicle/config' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置

export default {
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // loding
      columns: [
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '所属单位',
          ellipsis: true,
          dataIndex: 'unitName'
        },
        {
          title: '加油卡号',
          ellipsis: true,
          dataIndex: 'gasCardNumber'
        },
        {
          title: '车牌号',
          ellipsis: true,
          dataIndex: 'carNumber'
        },
        {
          title: '驾驶员',
          ellipsis: true,
          dataIndex: 'driver',
          customRender() {
            return arguments[1].driverName && arguments[1].phone
              ? arguments[1].driverName + ' ' + arguments[1].phone
              : '—'
          }
        },
        {
          title: '充值金额（元）',
          dataIndex: 'chargeAmount',
          width: '300px',
          scopedSlots: { customRender: 'chargeAmount' }
        }
      ],
      form: {}, // 表单
      rules: {
        chargeTime: [{ required: true, message: '请选择充值日期', trigger: 'change' }],
        // fileInfoVOS: [{ type: 'array', required: true, message: '请上传油卡转账凭证', trigger: 'blur' }]
      }, // 校验规则
      init: false // 初始化控件
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoVOS'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoVOS')
        })
      }
    }
  },
  mounted() {
    this.loading = true
    if (this.editModel == 0) {
      carGasCard
        .detail({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      // 映射登录人信息
      const post = this.$currentPost()
      this.$set(this.form, 'chargeTime', this.$dateFormat(new Date(), 'D'))
      this.$set(this.form, 'chargeUnitId', post.id)
      this.$set(this.form, 'chargeUnitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'officeHeadName', this.$userInfo()?.name)
      this.$set(this.form, 'officeHeadId', this.$userInfo()?.id)
      this.$set(this.form, 'phone', this.$userInfo()?.employee?.phone)
      // 获取加油卡信息
      carGasCard
        .getCarCards()
        .then((res) => {
          this.loading = false
          this.$set(this.form, 'itemVOS', res.data)
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    }
  },
  computed: {
    // 加油卡列表
    loadData() {
      return this.form.itemVOS || (this.form.chargeAmount ? [this.form] : [])
    },
    // 表单列表
    formList() {
      return [
        {
          keyName: 'chargeUnitName',
          type: 'BaseInput',
          disabled: true,
          label: '单位'
        },
        {
          keyName: 'officeHeadName',
          type: 'BaseInput',
          disabled: true,
          label: '办公室负责人'
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          disabled: true,
          label: '联系电话'
        },
        {
          keyName: 'chargeTime',
          label: '充值日期',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    }
  },
  methods: {
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (that.form.itemVOS.every((item) => !item.chargeAmount)) {
          that.$message.warning('请至少填写一个大于0的充值金额')
          return
        }
        if (e) {
          that.$confirm({
            title: '温馨提示',
            content: '请确认是否提交，提交后将不可再次修改',
            onOk: () => {
              let form = that.$clone(that.form)
              // 格式化文件
              if (form.fileInfoVOS?.length > 0) {
                form.file = form.fileInfoVOS?.map((item) => item.commonId)?.join()
                delete form.fileInfoVOS
              }
              // 格式化充值列表
              form.itemVOS = form.itemVOS.map((item) => ({
                carNumber: item.carNumber,
                chargeAmount: item.chargeAmount,
                driverId: item.driverId,
                driverName: item.driverName,
                gasCardNumber: item.gasCardNumber,
                unitId: item.unitId,
                unitName: item.unitName
              }))
              // 提交表单
              return carGasCard.create(form).then(() => {
                that.$message.success('提交成功！')
                that.$multiTab.close()
              })
            }
          })
        }
      })
    }
  }
}
</script>